/**
 * 多语言配置文件
 */
import I18n from 'i18n-js';
import * as RNLocalize from 'react-native-localize';
import en from '../locales/en-US';
import zh from '../locales/zh-CN';
import AsyncStorage from '@react-native-community/async-storage';
import RNRestart from 'react-native-restart';

// 获取手机本地国际化信息
const locales = RNLocalize.getLocales();
const systemLanguage = locales[0]?.languageCode; // 用户系统偏好语言
export const languageKey = 'language';

I18n.fallbacks = true;

// 加载语言包
I18n.translations = {
  zh,
  en,
};

/**
 * 初始化
 */
AsyncStorage.getItem(languageKey).then(value => {
  if (value) {
    I18n.locale = value;
  } else if (systemLanguage) {
    I18n.locale = systemLanguage;
  } else {
    I18n.locale = 'en';
  }
});

/**
 * 修改语言
 * @param {*} language 语言
 */
export async function changeLanguage(language) {
  await AsyncStorage.setItem(languageKey, language);
  // Immediately reload the React Native Bundle
  RNRestart?.Restart();
}

/**
 * 重置
 */
export async function resetLanguage() {
  await AsyncStorage.removeItem(languageKey);
  // Immediately reload the React Native Bundle
  RNRestart?.Restart();
}

export default I18n;
